package com.sync.syncmasterdata.dingrobot.service;

import com.aliyun.dingtalkrobot_1_0.*;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 钉钉机器人服务
 */
@Service
@Slf4j
public class DingRobotService {

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private DingUtilService dingUtilService;

    @Autowired
    private DingAPIService dingAPIService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthUtil authUtil;

    /**
     * 机器人传送 普通卡片形式 信息服务(officialActionCardMsg)
     * 展示语言是map:demo
     * cardDataCardParamMap.put("text", " ## 痞子姚测试机器人 \n " +
     * " ## 故障线索 \n " +
     * "1. 回复1 \n " +
     * "2. 回复2 \n " );
     * cardDataCardParamMap.put("title", "机器人测试消息");
     * cardDataCardParamMap.put("singleTitle", "查看详情");
     * cardDataCardParamMap.put("singleURL", "https://www.dingtalk.com/");
     *
     * users使用 list手机号
     */
    public void robotSendCardMsg(Map<String, String> map, List<String> users) {
        Config config = new Config();
        String access_token = null;
        config.protocol = "https";
        config.regionId = "central";
        Client client = null;
        try {
            client = new Client(config);
//            access_token = dingUtilService.getToken();
            access_token = authUtil.getCPTokenByTag("dingrobottag");
            BatchSendOTOHeaders headers = new BatchSendOTOHeaders();
            headers.xAcsDingtalkAccessToken = (access_token);
            BatchSendOTORequest request = new BatchSendOTORequest().setRobotCode(this.confInfo.getRebotKey()).setUserIds(users).setMsgKey("officialActionCardMsg").setMsgParam(objectMapper.writeValueAsString(map));
            BatchSendOTOResponse rsp = client.batchSendOTOWithOptions(request, headers, new RuntimeOptions());
            log.info("DingRobotService打印请求后返回：{}", objectMapper.writeValueAsString(rsp));

        } catch (Exception ex) {
            TeaException err = new TeaException(ex.getMessage(), ex);

            ex.printStackTrace();
            log.info(err.getData().toString());
        }

    }

    /**
     * 机器人传送 简单信息服务（留言形式）(sampleText)
     * 展示语言是map:demo
     * cardDataCardParamMap.put("content", " 我爱北京天安门 " );
     * users使用 list手机号
     */
    public void robotSendSampleMsg(Map<String,String> map,List<String> users){

        Config config = new Config();
        String access_token = null;
        config.protocol = "https";
        config.regionId = "central";
        Client client = null;
        try {
            client = new Client(config);
//            access_token = dingUtilService.getToken();
            access_token = authUtil.getCPTokenByTag("dingrobottag");
            BatchSendOTOHeaders headers = new BatchSendOTOHeaders();
            headers.xAcsDingtalkAccessToken = (access_token);
            BatchSendOTORequest request = new BatchSendOTORequest().setRobotCode(this.confInfo.getRebotKey()).setUserIds(users).setMsgKey("sampleText").setMsgParam(objectMapper.writeValueAsString(map));
            BatchSendOTOResponse rsp = client.batchSendOTOWithOptions(request, headers, new RuntimeOptions());
            log.info("DingRobotService打印请求后返回：{}", objectMapper.writeValueAsString(rsp));

        } catch (Exception ex) {
            TeaException err = new TeaException(ex.getMessage(), ex);

            ex.printStackTrace();
            log.info(err.getData().toString());
        }
    }

    /**
     * 机器人传送 简单图片文件服务（留言形式）(sampleText)
     * 展示语言是map:demo
     * cardDataCardParamMap.put("photoURL", " https://www.baidu.com " );
     * users使用 list手机号
     */
    public void robotSendSampleImageMsg(Map<String,String> map,List<String> users){

        Config config = new Config();
        String access_token = null;
        config.protocol = "https";
        config.regionId = "central";
        Client client = null;
        try {
            client = new Client(config);
//            access_token = dingUtilService.getToken();
            access_token = authUtil.getCPTokenByTag("dingrobottag");
            BatchSendOTOHeaders headers = new BatchSendOTOHeaders();
            headers.xAcsDingtalkAccessToken = (access_token);
            BatchSendOTORequest request = new BatchSendOTORequest().setRobotCode(this.confInfo.getRebotKey()).setUserIds(users).setMsgKey("sampleImageMsg").setMsgParam(objectMapper.writeValueAsString(map));
            BatchSendOTOResponse rsp = client.batchSendOTOWithOptions(request, headers, new RuntimeOptions());
            log.info("DingRobotService打印请求后返回：{}", objectMapper.writeValueAsString(rsp));

        } catch (Exception ex) {
            TeaException err = new TeaException(ex.getMessage(), ex);
            ex.printStackTrace();
            log.info(err.getData().toString());
        }
    }

    /**
     * 机器人传送 简单图片文件服务（留言形式）(sampleText)
     * 展示语言是map:demo
     * cardDataCardParamMap.put("title", "title" );
     * cardDataCardParamMap.put("text", "text" );
     * cardDataCardParamMap.put("singleTitle", "singleTitle" );
     * cardDataCardParamMap.put("singleURL", "singleURL" );
     * users使用 list手机号
     */
    public void robotSendSampleLinkMsg(Map<String,String> map,List<String> users){

        Config config = new Config();
        String access_token = null;
        config.protocol = "https";
        config.regionId = "central";
        Client client = null;
        try {
            client = new Client(config);
//            access_token = dingUtilService.getToken();
            access_token = authUtil.getCPTokenByTag("dingrobottag");
            BatchSendOTOHeaders headers = new BatchSendOTOHeaders();
            headers.xAcsDingtalkAccessToken = (access_token);
            BatchSendOTORequest request = new BatchSendOTORequest().setRobotCode(this.confInfo.getRebotKey()).setUserIds(users).setMsgKey("sampleLink").setMsgParam(objectMapper.writeValueAsString(map));
            BatchSendOTOResponse rsp = client.batchSendOTOWithOptions(request, headers, new RuntimeOptions());
            log.info("DingRobotService打印请求后返回：{}", objectMapper.writeValueAsString(rsp));

        } catch (Exception ex) {
            TeaException err = new TeaException(ex.getMessage(), ex);
            ex.printStackTrace();
            log.info(err.getData().toString());
        }
    }

    /**
     * 钉钉 机器人对话 简化版
     * @param msg   信息
     * @param userPhone 用户手机号 new String[]{"15267167276","15903019297"} 需要作废
     */
    public void simpleDingSendMsg(String msg, String[] userPhone) {
        if (StringUtils.isBlank(msg) || userPhone.length==0) {
            return;
        }
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("content", msg);
        robotSendSampleMsg(msgMap, dingAPIService.convertPhoneToUseridList(Arrays.asList(userPhone)));
    }

}
